<?php

/**
 * @Author: king
 * @Date:   2019-05-20 15:09:04
 * @Last Modified by:   king
 * @Last Modified time: 2019-05-30 23:02:15
 */

namespace App\Tools;
use App\Models\Api\MessageCenter;
use App\Models\Api\LanmeiCounselorCheck;
use App\Models\Api\LanmeiCounselor;
use App\Models\Api\LanmeiCounselorInfo;
use App\Models\Api\LanmeiUserCounselorStatus;
use Illuminate\Contracts\Queue\Job;

class IdentityJob
{
    public function task1(Job $job,$data)
    {

        try{
            $data = (new LanmeiCounselorCheck())->select('id','uid','left_pic','right_pic','truename','telphone','id_number','ali_number')->where('id',$id)->first();

        }catch(\Exception $e)
        {
          \Log::info('IdentityJob:' . $e->getMessage());
         }
        $host = Util::getLocalMachineFlag();
         \Log::info($host . PHP_EOL . '身份验证开始 ' . date('Y-m-d H:i:s') . PHP_EOL);
        print_r($host . PHP_EOL . '身份验证开始 ' . date('Y-m-d H:i:s') . PHP_EOL);
        if ($job->attempts() > 1)
        {
            $job->delete();// 任务重复执行1次以上  删除该任务
        }
        $face_side = $data['left_pic'];
        $back_side = $data['right_pic'];

        //1. 调用阿里身份证验证接口
        $face = $this->checkInfo($face_side, $side = 0);
        $back = $this->checkInfo($back_side, $side = 1);

        $face = json_decode($face, true);
        $back = json_decode($back, true);

        if ($face && $back && $data)
        {

            if ($face['name'] === $data['truename'] && $face['num'] === $data['id_number'] && strtotime($back['end_date']) > time())
            {

                //后台通过审核后向咨询师表，咨询师信息表（审核通过后）中添加咨询师数据
                $LanmeiCounselor = new LanmeiCounselor() ;
                $LanmeiCounselor->create($data);
                $cid = $LanmeiCounselor->id;
                (new LanmeiCounselorInfo())->create($data);
                //修改咨询师状态表的审核状态
                (new LanmeiUserCounselorStatus())->save(['uid'=>$data['uid'],'is_check'=>1,'c_id'=>$cid]);
                //审核通过后修改CounselorCheck的状态为已通过
                (new LanmeiCounselorCheck())->where('id',$data['id'])->save(['status'=>3]);
                // 消息中心添加信息
                $mag = [
                    'uid' => $data['uid'],
                    'type' => 1,
                    'cid' => 1,
                    'title' => '咨询师审核结果',
                    'content' =>'您提交的咨询师材料已通过审核，点击查看审核详情！',
//                                'link' => 'rectification_details?id=' . $reid,
                    'target' => "local",
                ];
                (new MessageCenter())->pushMessage($mag);
            }else
            {
                //修改审核状态为队列审核失败
                (new LanmeiCounselorCheck())->where('id',$data['id'])->save(['status'=>4]);
            }
        }else
        {
            //修改审核状态为队列审核失败
            (new LanmeiCounselorCheck())->where('id',$data['id'])->save(['status'=>4]);
        }
        //如果任务执行成功后 记得删除任务，不然这个任务会重复执行，直到达到最大重试次数后失败后，执行failed方法
        $job->delete();
    }


    /**
     * 阿里身份证验证
     */
    private function checkInfo($path, $side)
    {
        $url = "https://dm-51.data.aliyun.com/rest/160601/ocr/ocr_idcard.json";
        //TODO 填写appcode
        $appcode = "你的APPCODE";
        $file = $path;//你的文件路径
        //如果输入带有inputs, 设置为True，否则设为False
        $is_old_format = false;
        //如果没有configure字段，config设为空
        if ($side == 0)
        {
            $config = array(
                "side" => "face"
            );
        }
        if ($side == 1)
        {
            $config = array(
                "side" => "back"
            );
        }
        //$config = array()
        if ($fp = fopen($file, "rb", 0))
        {
            $binary = fread($fp, filesize($file)); // 文件读取
            fclose($fp);
            $base64 = base64_encode($binary); // 转码
        }
        $headers = array();
        array_push($headers, "Authorization:APPCODE " . $appcode);
        //根据API的要求，定义相对应的Content-Type
        array_push($headers, "Content-Type" . ":" . "application/json; charset=UTF-8");
        $querys = "";
        if ($is_old_format == true)
        {
            $request = array();
            $request["image"] = array(
                "dataType" => 50,
                "dataValue" => "$base64"
            );

            if (count($config) > 0)
            {
                $request["configure"] = array(
                    "dataType" => 50,
                    "dataValue" => json_encode($config)
                );
            }
            $body = json_encode(array("inputs" => array($request)));
        } else
        {
            $request = array(
                "image" => "$base64"
            );
            if (count($config) > 0)
            {
                $request["configure"] = json_encode($config);
            }
            $body = json_encode($request);
        }
        $method = "POST";
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, true);
        if (1 == strpos("$" . $url, "https://"))
        {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }
        curl_setopt($curl, CURLOPT_POSTFIELDS, $body);
        $result = curl_exec($curl);
        $header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
        $rheader = substr($result, 0, $header_size);
        $rbody = substr($result, $header_size);

        $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        if ($httpCode == 200)
        {
            if ($is_old_format)
            {
                $output = json_decode($rbody, true);
                $result_str = $output["outputs"][0]["outputValue"]["dataValue"];
                return $result_str;
            } else
            {
                $result_str = $rbody;
                return $result_str;
            }
//            printf("result is :\n %s\n", $result_str);
        } else
        {
//            printf("Http error code: %d\n", $httpCode);
//            printf("Error msg in body: %s\n", $rbody);
//            printf("header: %s\n", $rheader);

            $result = [$httpCode, $rbody, $rheader];
            return json_encode($result, true);
        }
    }
}